package com.appkubes.mall.admin.application.goods.stage;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.appkubes.common.utils.data.date.DateUtils;
import com.appkubes.common.utils.data.string.UUIDUtils;
import com.appkubes.mall.admin.application.goods.goods.dao.GoodsStageDao;
import com.appkubes.mall.core.po.MallGoodsStage;
import com.appkubes.mall.core.po.MallGoodsStageExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class GoodsStageService {

    @Autowired
    GoodsStageDao stageDao;

    public List<MallGoodsStage> queryById(String goodKey) {
        MallGoodsStageExample example = new MallGoodsStageExample();
        MallGoodsStageExample.Criteria criteria = example.createCriteria();
        criteria.andGoodKeyEqualTo(goodKey);
        return stageDao.selectByExample(example);
    }

    public void insertAll(JSONArray updateArray, String goodKey) {
        this.insertOrUpdateAll(updateArray, goodKey);
    }

    private void insertOrUpdateAll(JSONArray array, String goodKey) {
        for (int i=0; i<array.size(); i++) {
            JSONObject jsonObject = array.getJSONObject(i);
            if (jsonObject.getString("id") == null || Integer.parseInt(jsonObject.getString("id")) == -1) {
                MallGoodsStage MallGoodsStage = new MallGoodsStage();
                MallGoodsStage.setCreateTime(DateUtils.DateToTimestamp(new Date()));
                MallGoodsStage.setUpdateTime(DateUtils.DateToTimestamp(new Date()));
                MallGoodsStage.setGoodKey(goodKey);
                MallGoodsStage.setChecked(jsonObject.getByte("checked"));
                MallGoodsStage.setMonths(Integer.parseInt(jsonObject.getString("months")));
                MallGoodsStage.setRate( jsonObject.getBigDecimal("rate") );
                MallGoodsStage.setGoodsStageKey(UUIDUtils.getUUID());
                MallGoodsStage.setAppKey(null);
                stageDao.insertSelective(MallGoodsStage);
            } else {
                MallGoodsStage MallGoodsStage = new MallGoodsStage();
                MallGoodsStage.setGoodsStageKey(UUIDUtils.getUUID());
                MallGoodsStage.setGoodKey(goodKey);
                MallGoodsStage.setCreateTime(DateUtils.DateToTimestamp(new Date()));
                MallGoodsStage.setUpdateTime(DateUtils.DateToTimestamp(new Date()));
                MallGoodsStage.setChecked(jsonObject.getByte("checked"));
                MallGoodsStage.setMonths(Integer.parseInt(jsonObject.getString("months")));
                MallGoodsStage.setRate( jsonObject.getBigDecimal("rate") );
                MallGoodsStage.setGoodsStageKey(UUIDUtils.getUUID());
                stageDao.updateByPrimaryKeySelective(MallGoodsStage);
            }
        }
    }
}
